#include <assert.h>
#include <QDebug>
#include "shader_program.h"
#include "res_helper.h"

ShaderProgram::ShaderProgram(const char* vetexShaderSrc, const char* fragmentShaderSrc) {
    initializeOpenGLFunctions();
    // 顶点着色器
    ResHelper vertexHelper(vetexShaderSrc);
    QString &vertexSrc = vertexHelper.getContent();
    m_vshader = new QOpenGLShader(QOpenGLShader::Vertex);
    // 编译问题会自动报错
    bool r = m_vshader->compileSourceCode(vertexSrc);
    assert(r);
    // 片段着色器
    ResHelper fragHelper(fragmentShaderSrc);
    QString &fragSrc = fragHelper.getContent();
    m_fshader = new QOpenGLShader(QOpenGLShader::Fragment);
    r = m_fshader->compileSourceCode(fragSrc);
    assert(r);
    // 着色器程序
    m_program = new QOpenGLShaderProgram();
    m_program->addShader(m_vshader);
    m_program->addShader(m_fshader);
    m_program->link();
    // 着色器变量
    initLocations();
}

void ShaderProgram::initLocations() {
    // 属性在program中的位置
    m_aPostion = m_program->attributeLocation("a_Position");
    m_uMatrix = m_program->uniformLocation("u_Matrix");
}

ShaderProgram::~ShaderProgram() {
    delete m_program;
    delete m_vshader;
    delete m_fshader;
}
